package ecs

type Component interface {
	Mask() uint64
}

var idGen = uint64(0)

type EntityId int64

type Entity struct {
	components []Component
	id         EntityId
	mask       uint64
}

func (e *Entity) Id() EntityId {
	return e.id
}

func (e *Entity) Mask() uint64 {
	return e.mask
}

// 注意需要自己保证不添加重复的Component
func NewEntity(components []Component) *Entity {
	idGen++
	return &Entity{
		components: components,
		id:         EntityId(idGen),
		mask:       maskSlice(components),
	}
}

func maskSlice(components []Component) uint64 {
	mask := uint64(0)
	for _, c := range components {
		mask = mask | c.Mask()
	}
	return mask
}

func (e *Entity) Add(comp ...Component) {
	for _, c := range comp {
		// 单一Component
		if e.mask&c.Mask() == c.Mask() {
			continue
		}
		e.components = append(e.components, c)
		e.mask = maskSlice(e.components)
	}
}

func (e *Entity) Get(mask uint64) Component {
	for _, c := range e.components {
		if c.Mask() == mask {
			return c
		}
	}
	return nil
}

func (e *Entity) Remove(mask uint64) {
	modified := false
	for i, c := range e.components {
		if c.Mask() == mask {
			e.components = append(e.components[:i], e.components[i+1:]...)
			modified = true
			break
		}
	}
	if modified {
		e.mask = maskSlice(e.components)
	}
}
